package com.chenxi.provider;

import com.chenxi.model.SysOauthClient;
import com.chenxi.service.ISysOauthClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Set;

@Service(value = "myClientDetailsService")
public class MyClientDetailsService implements ClientDetailsService {

    @Autowired
    private ISysOauthClientService sysOauthClientService;
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        SysOauthClient sysOauthClient = sysOauthClientService.loadClientByClientId(clientId);
        BaseClientDetails clientDetails = new BaseClientDetails(sysOauthClient.getClientId(),
                sysOauthClient.getResourceIds(),
                sysOauthClient.getScope(),sysOauthClient.getAuthorizedGrantTypes(),
                sysOauthClient.getAuthorities(),sysOauthClient.getRegisteredRedirectUri());
        clientDetails.setClientSecret(sysOauthClient.getClientSecret());
        clientDetails.setAccessTokenValiditySeconds(sysOauthClient.getAccessTokenValidity());
        clientDetails.setRefreshTokenValiditySeconds(sysOauthClient.getRefreshTokenValidity());
        if (StringUtils.hasText(sysOauthClient.getAutoApprove())) {
            Set<String> autoApprove = StringUtils
                    .commaDelimitedListToSet(sysOauthClient.getAutoApprove());
            if (!autoApprove.isEmpty()) {
                clientDetails.setAutoApproveScopes(autoApprove);
            }
        }
        return clientDetails;
    }
}
